#include "mqtt-net-communication.h"

MQTTNetCommunication::MQTTNetCommunication(const string &host, uint16_t port) : MQTTClient("/mqtt/send/message/topic",
                                                                                           "/mqtt/recv/message/topic",
                                                                                           0)
{
    bool ok = this->connect(host, port);
    if (!ok)
    {
        fprintf(stderr, "Fail to mqtt connect\n");
        return;
    }
}

MQTTNetCommunication::~MQTTNetCommunication()
{
    bool ok = this->disconnect();
    if (!ok)
    {
        fprintf(stderr, "Fail to mqtt disconnect\n");
        return;
    }
}

bool MQTTNetCommunication::sendPacket(const vector<uint8_t> &packet)
{
    int ret = this->send(packet.data(), packet.size());
    if (ret < 0)
    {
        fprintf(stderr, "Fail to mqtt send\n");
        return false;
    }
    return true;
}

bool MQTTNetCommunication::recvPacket(vector<uint8_t> &packet, int timeout)
{
    char buf[1024];
    int size = this->recv(buf, sizeof(buf));
    if (size < 0)
    {
        fprintf(stderr, "Fail to mqtt recv\n");
        return false;
    }
    // char 转vector
    packet.assign(buf, buf + size);

    return true;
}
